/*
 PureMVC AS3 Demo - Flex Application Skeleton 
 Copyright (c) 2007 Daniele Ugoletti <daniele.ugoletti@puremvc.org>
 Your reuse is governed by the Creative Commons Attribution 3.0 License
*/
package com.swiftair.model.delegates
{	
	import com.adobe.serialization.json.JSON;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class JSONDelegate implements IResponder
	{
		private var _proxy:Proxy;
		private var _notification:String;
		private var _service:HTTPService;
		private var _params:Object;
		
		public function JSONDelegate(proxy:Proxy, url:String, params:Object=null) {
			// constructor will store a reference to the service we're going to call
			_service = new HTTPService();
			_service.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
			_service.url = url;

			_params = params;
			
			// and store a reference to the proxy that created this delegate
			this._proxy = proxy;
		}

		public function load(notification:String):void {
			// call the service
			var token:AsyncToken = _service.send(_params);
			_notification = notification;
			// notify this responder when the service call completes
			token.addResponder(this);
		}

		public function result(data:Object):void {
			var tweets:Array;
			
			try {
				tweets = JSON.decode(data.result as String) as Array;
			} catch(parseError:Error) {
				trace("parse error");
			}
			_proxy.sendNotification(_notification, new ArrayCollection(tweets));
		}
		
		public function fault(info:Object):void {
			trace(info.faultString);
		}
	}
}